using UnityEngine;
using System.Collections;
using System.Threading;
public class LoggingScript : MonoBehaviour {
	bool waitForit = true;
	float amountofTime = 5.0F;
	int frameTime = 10;
	int i = 0;
	int j = 0;
	string names;
	Thread LogThread;
	int life = 100;
	
	 ArrayList queueArea = new ArrayList();
	
	
	// Use this for initialization
	void Start () {
	names = transform.name.ToString();
	Debug.Log("Calling Flush");
	StartCoroutine(FlushTimer());
	Debug.Log("Called Flush");	
	StartCoroutine(QueueUp());
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	
	public void LogitAway()
	{
		lock(this)
		{
		Debug.Log("Working "+i);
		i++;
		for(int k = 0;k<queueArea.Capacity;k++)
			{
				
				string current = queueArea[k].ToString();
				System.IO.File.AppendAllText("C:/logof" +names+".txt",current+'\n');
			}
			queueArea.Clear();
		return;
		}
	}
	
	public IEnumerator FlushTimer()
	{
		Debug.Log("Flush Starting");
		while(true)
		{
			LogThread = new Thread(LogitAway);
		yield return new WaitForSeconds(amountofTime);
			Debug.Log("Thread Starting");
		LogThread.Start();
			Debug.Log("Started" + i);
			Debug.Log("Ended");
			
		}
	}
	
	public IEnumerator QueueUp()
	{
		while(true)
		{
			for (int i=0; i<frameTime; i++)
			{
    		yield return null;
			}
			string now = ("Location: "+transform.position.x+" , "+transform.position.y+" , "+transform.position.z+" , Rotation: " + transform.rotation.x+" , "+ transform.rotation.y+" , "+ transform.rotation.z+" , Scale: "+transform.localScale.x+" , "+transform.localScale.y+" , " +transform.localScale.z+" Life: " +life);
			queueArea.Add(now);
			Debug.Log("Added New Info " + j);
			j++;
		}
		
		
	}
	
	void OnApplicationQuit()
	{
		if(LogThread.IsAlive)
		{
		LogThread.Join();
		}
	}
		
	void OnCollisionEnter(Collision collision)
	{
		string now = ("Location: "+transform.position.x+" , "+transform.position.y+" , "+transform.position.z+" , Rotation: " + transform.rotation.x+" , "+ transform.rotation.y+" , "+ transform.rotation.z+" , Scale: "+transform.localScale.x+" , "+transform.localScale.y+" , " +transform.localScale.z+" Life: " +life);
			queueArea.Add(now);
		Debug.Log("Added New Info Col");
	}
	
	 void OnTriggerEnter(Collider other)
	{
		string now = ("Location: "+transform.position.x+" , "+transform.position.y+" , "+transform.position.z+" , Rotation: " + transform.rotation.x+" , "+ transform.rotation.y+" , "+ transform.rotation.z+" , Scale: "+transform.localScale.x+" , "+transform.localScale.y+" , " +transform.localScale.z+" Life: " +life);
			queueArea.Add(now);
		Debug.Log("Added New Info Trig");
	}
	
	
	
}

